/*    This file is part of libmissive.
 *
 *    libmissive is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU Lesser General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    libmissive is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public License
 *    along with libmissive.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <string.h>

#include "seal.h"

int
msg_seal(Msg *msg, const Box_pkey their_pkey)
{
	size_t seal_len = msg->len + crypto_box_SEALBYTES;
	unsigned char *sealed = malloc(seal_len);

	if (!sealed)
		return -1;

	if (crypto_box_seal(sealed, msg->buf, msg->len, their_pkey)) {
		free(sealed);
		return -1;
	}

	msg_dispose(msg);
	msg_send_init(msg, seal_len, sealed, 1);
	return 0;
}

int
msg_unseal(Msg *msg, const Box_skey my_skey, const Box_pkey my_pkey)
{
	unsigned char *unsealed;
	ssize_t unseal_len = (ssize_t) msg->len -
		(ssize_t) crypto_box_SEALBYTES;

	if (unseal_len < 0)
		return -1;

	if (!(unsealed = malloc(unseal_len)))
		return -1;

	if (crypto_box_seal_open(unsealed, msg->buf,
				 msg->len, my_pkey, my_skey)) {
		free(unsealed);
		return -1;
	}

	msg_dispose(msg);
	msg_send_init(msg, unseal_len, unsealed, 1);
	return 0;
}

int
unsealer_add(Msg *msg, const Box_pkey their_pkey)
{
	size_t len = msg->len + sizeof(Box_pkey);
        unsigned char *buf = realloc(msg->buf, len);

	if (!buf)
		return -1;

	memcpy(buf + msg->len, their_pkey, sizeof(Box_pkey));
	msg->buf = buf;
	msg->len = len;
	return 0;
}

int
unsealer_remove(Msg *msg, Box_pkey their_pkey)
{
	if (unsealer_get(msg, their_pkey) < 0)
		return -1;

	msg->len -= sizeof(Box_pkey);
	return 0;
}

int
unsealer_get(const Msg *msg, Box_pkey their_pkey)
{
	if (msg->len < sizeof(Box_pkey))
		return -1;

	if (their_pkey)
		memcpy(their_pkey,
		       (char *) msg->buf + msg->len - sizeof(Box_pkey),
		       sizeof(Box_pkey));

	return 0;
}

int
unsealer_seal(Msg *msg, const Box_pkey their_pkey)
{
	Err err;
	Msg copy;

	if (msg_copy(&copy, msg, &err) < 0)
		return -1;

	if (msg_seal(&copy, their_pkey) < 0 ||
	    unsealer_add(msg, their_pkey) < 0) {
		msg_dispose(&copy);
		return -1;
	}

	msg_dispose(msg);
	*msg = copy;
	return 0;
}
